package com.qf.sportsevent.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.qf.sportsevent.R;
import com.qf.sportsevent.activity.SubscribeActivity;
import com.qf.sportsevent.adapter.CommonFragmentPagerAdapter;
import com.qf.sportsevent.databinding.FragmentNewsBinding;
import com.qf.sportsevent.entity.TitleChannelEntity;
import com.qf.sportsevent.entity.TitleEntity;
import com.qf.sportsevent.util.FastEventBus;
import com.qf.sportsevent.util.HttpUtils;
import com.qf.sportsevent.util.UrlManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFragment extends Fragment implements Callback, View.OnClickListener {
    private FragmentNewsBinding binding;
    private FragmentManager fragmentManager;
    private List<String> channelNames;
    private CommonFragmentPagerAdapter<TitleChannelEntity> adapter;
    private List<TitleChannelEntity> channels;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_news, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        fragmentManager = getFragmentManager();
        binding.newsTab.setupWithViewPager(binding.newsPager);
        binding.newsSubscribe.setOnClickListener(this);
        HttpUtils.okHttpAsyncGet(UrlManager.TitlesUrl,this);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
            String jsonStr = response.body().string();
            TitleEntity titleEntity = JSON.parseObject(jsonStr, TitleEntity.class);

            FastEventBus bus = new FastEventBus();
            bus.setTitleEntity(titleEntity);
            bus.setTag("title");
            EventBus.getDefault().post(bus);
    }

    @Override
    public void onFailure(Call call, IOException e) {}

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBusArrived(FastEventBus bus) {
        if(bus.getTag() !=null && bus.getTag() .equals("subscribe")){
            List<Integer> subscribeIndexs = bus.getSubscribeIndexs();
            List<TitleChannelEntity> changedChannels = new ArrayList<>();
            for (int i = 0; i < subscribeIndexs.size(); i++) {
                changedChannels.add(channels.get(subscribeIndexs.get(i)));
            }
            Log.d("2121",changedChannels.size()+"");
            channelNames.clear();
            for (int i = 0; i < changedChannels.size(); i++) {
                channelNames.add(changedChannels.get(i).getName());
            }
            adapter.updateList(changedChannels);
        }
        if(bus.getTag() != null && bus.getTag().equals("title")){
            TitleEntity titleEntity = bus.getTitleEntity();
            if (titleEntity != null) {
                channels = titleEntity.getData().getChannels();
                channelNames=new ArrayList<>();
                for (TitleChannelEntity channel : channels) {
                    channelNames.add(channel.getName());
                }
                adapter = new CommonFragmentPagerAdapter<>(fragmentManager, channels);
                binding.newsPager.setAdapter(adapter);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onClick(View view) {
        if (channelNames != null && channelNames.size()>0) {
            Intent intent = new Intent(getContext(), SubscribeActivity.class);
            intent.putStringArrayListExtra("channelNames", (ArrayList<String>) channelNames);
            startActivity(intent);
        }
    }
}
